Abstraction in C++
Abstraction is a fundamental concept in Object-Oriented Programming (OOP) that involves simplifying complex systems by modeling classes based on their essential properties and behaviors, while hiding the unnecessary details. In C++, abstraction is implemented through abstract classes and pure virtual functions.
Abstract Class:
An abstract class is a class that cannot be instantiated on its own. It often contains one or more pure virtual functions. Abstract classes are used as a foundation for derived classes.
public:
// Pure virtual function
virtual void draw() const = 0;
// Regular member function
void move() {
cout << "Moving the shape" << endl;
}
};
Pure Virtual Function:
A pure virtual function is a virtual function that has no implementation in the base class. It is declared using virtual returnType functionName() = 0;. Derived classes must provide their own implementation for pure virtual functions.
public:
// Pure virtual function
virtual void draw() const = 0;
};
class Circle : public Shape {
public:
// Override the pure virtual function
void draw() const override {
cout << "Drawing a circle" << endl;
}
};
Benefits of Abstraction:
(a). Code Simplification: Abstract classes focus on the essential aspects of an object, hiding unnecessary details. This simplifies the code and makes it more comprehensible.
(b). Flexibility and Extensibility: Abstract classes provide a flexible foundation for derived classes to extend functionality. New derived classes can be easily added without modifying existing code.
(c). Enforcement of Structure: Abstract classes define a structure that derived classes must adhere to.This enforces a consistent design across related classes.
Example of Abstraction in C++:
using namespace std;
// Abstract class
class Shape {
public:
// Pure virtual function
virtual void draw() const = 0;
// Regular member function
void move() {
cout << "Moving the shape" << endl;
}
};
// Concrete class derived from Shape
class Circle : public Shape {
public:
// Override the pure virtual function
void draw() const override {
cout << "Drawing a circle" << endl;
}
};
int main() {
// Creating objects
Circle myCircle;
// Calling member functions
myCircle.move();
myCircle.draw();
return 0;
}
In this example, the Shape class is an abstract class with a pure virtual function draw(). The Circle class is a concrete class derived from Shape and provides its own implementation of the draw() function. The move() function is a regular member function inherited from the Shape class
Using this abstraction, we can create various shapes (such as rectangles, triangles, etc.) by deriving new classes from the abstract Shape class, ensuring that each shape has its own implementation of the draw() function while inheriting common functionality from the abstract base class.